const { Client } = require('ssh2');
const { ipcMain } = require('electron');
const { BrowserWindow } = require('electron');

// 存储活动连接
const activeConnections = new Map();

// 初始化SSH连接处理
function initSshHandlers() {
  // 处理SSH连接请求
  ipcMain.on('ssh-connect', (event, connectionInfo) => {
    // console.log('Received SSH connect request:', connectionInfo);

    const { id: connectionId, host, port, username, authType, password, privateKey } = connectionInfo;
    
    // 创建SSH客户端
    const conn = new Client();
    
    // 存储连接信息
    activeConnections.set(connectionId, {
      connection: conn,
      webContents: event.sender
    });
    
    // 连接配置
    const config = {
      host,
      port,
      username,
      readyTimeout: 10000, // 10秒超时
    };
    
    // 根据认证类型设置认证方式
    if (authType === 'password') {
      config.password = password;
    } else if (authType === 'privateKey') {
      config.privateKey = privateKey;
    }
    
    // 连接事件处理
    conn.on('ready', () => {
      // 获取当前连接的webContents
      const connInfo = activeConnections.get(connectionId);
      if (connInfo && connInfo.webContents) {
        // 通知渲染进程连接成功
        connInfo.webContents.send('ssh-status', {
          connectionId,
          status: 'connected',
          message: '连接成功'
        });
      }
      
      // 创建Shell会话
      conn.shell((err, stream) => {
        if (err) {
          // 获取当前连接的webContents
          const connInfo = activeConnections.get(connectionId);
          if (connInfo && connInfo.webContents) {
            // 发送错误信息到对应的渲染进程
            connInfo.webContents.send('ssh-status', {
              connectionId,
              status: 'error',
              message: `无法创建Shell: ${err.message}`
            });
          }
          return;
        }
        
        // 存储流
        activeConnections.get(connectionId).stream = stream;
        
        // 处理数据
        stream.on('data', (data) => {
          // 获取当前连接的webContents
          const connInfo = activeConnections.get(connectionId);
          if (connInfo && connInfo.webContents) {
            // 发送数据到对应的渲染进程
            connInfo.webContents.send('ssh-data', {
              connectionId,
              output: data.toString('utf8')
            });
          }
        });
        
        // 处理关闭
        stream.on('close', () => {
          // 获取当前连接的webContents
          const connInfo = activeConnections.get(connectionId);
          if (connInfo && connInfo.webContents) {
            // 发送状态更新到对应的渲染进程
            connInfo.webContents.send('ssh-status', {
              connectionId,
              status: 'disconnected'
            });
          }
          
          // 关闭连接
          if (activeConnections.has(connectionId)) {
            const conn = activeConnections.get(connectionId).connection;
            if (conn) conn.end();
            activeConnections.delete(connectionId);
          }
        });
        
        // 处理错误
        stream.on('error', (err) => {
          // 获取当前连接的webContents
          const connInfo = activeConnections.get(connectionId);
          if (connInfo && connInfo.webContents) {
            // 发送错误信息到对应的渲染进程
            connInfo.webContents.send('ssh-status', {
              connectionId,
              status: 'error',
              message: err.message
            });
          }
        });
      });
    });
    
    // 处理错误
    conn.on('error', (err) => {
      // 获取当前连接的webContents
      const connInfo = activeConnections.get(connectionId);
      if (connInfo && connInfo.webContents) {
        // 发送错误信息到对应的渲染进程
        connInfo.webContents.send('ssh-status', {
          connectionId,
          status: 'error',
          message: err.message
        });
      }
      
      // 清理连接
      if (activeConnections.has(connectionId)) {
        activeConnections.delete(connectionId);
      }
    });
    
    // 开始连接
    conn.connect(config);
  });
  
  // 处理SSH断开连接请求
  ipcMain.on('ssh-disconnect', (event, data) => {
    // 添加参数验证，防止解构undefined对象
    if (!data) {
      console.error('收到无效的ssh-disconnect请求：data为undefined');
      return;
    }
    
    const { connectionId } = data;
    if (activeConnections.has(connectionId)) {
      const { connection } = activeConnections.get(connectionId);
      if (connection) {
        connection.end();
      }
      activeConnections.delete(connectionId);
      
      // 获取当前连接的webContents
      const connInfo = activeConnections.get(connectionId);
      if (connInfo && connInfo.webContents) {
        // 通知渲染进程连接已断开
        connInfo.webContents.send('ssh-status', {
          connectionId,
          status: 'disconnected'
        });
      }
    }
  });
  
  // 处理SSH数据发送请求
  ipcMain.on('ssh-data', (event, data) => {
    // 添加参数验证，防止解构undefined对象
    if (!data) {
      console.error('收到无效的ssh-data请求：data为undefined');
      return;
    }
    
    const { connectionId, input } = data;
    if (activeConnections.has(connectionId)) {
      const { stream } = activeConnections.get(connectionId);
      if (stream) {
        stream.write(input);
      }
    }
  });
}

// 导出初始化函数
module.exports = { initSshHandlers };